package com.distribute.core.netty.handler;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.distribute.common.MsgObj;
import com.distribute.common.MsgType;
import com.distribute.common.ReportEntity;
import com.distribute.core.constants.LocalCacheConstants;
import com.distribute.core.core.CacheManageContext;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 缓存内存上报
 *
 * @author chennengcheng
 * @date 2021-09-22 16:44
 * @remark
 */

@ChannelHandler.Sharable
public class CacheMemoryInfoHandler extends ChannelInboundHandlerAdapter {

    private static final Logger log = LoggerFactory.getLogger(CacheMemoryInfoHandler.class);
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        Channel channel = ctx.channel();
        ping(channel);
    }

    private void ping(Channel channel) {
        channel.eventLoop().scheduleAtFixedRate(() -> {
            // 如果通道正常
            if (channel.isActive()) {
                String msg = reportSelf();
                if (StrUtil.isBlank(msg)) {
                    return;
                }

                channel.writeAndFlush(msg);
            } else {
                channel.closeFuture();
                throw new RuntimeException();
            }

        }, 1, LocalCacheConstants.getReportTime(), TimeUnit.SECONDS);
    }

    /**
     * 上报自身信息
     */
    public String reportSelf(){
        List<ReportEntity> reportEntityList = CacheManageContext.getReportEntityList();
        if (CollectionUtil.isEmpty(reportEntityList)) {
            return "没有消息";
        }

        MsgObj msgObj = new MsgObj(MsgType.CACHE_INFO_TYPE, JSONUtil.toJsonStr(reportEntityList));
       return JSONUtil.toJsonStr(msgObj);
    }
}
